package com.example.demo;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;

import static com.netflix.zuul.context.RequestContext.getCurrentContext;

public class TokenValidZuulFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(TokenValidZuulFilter.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        try {
            RequestContext context = getCurrentContext();
            HttpServletRequest request = context.getRequest();
            String timestamp = request.getParameter("timestamp");
            String accessKey = request.getParameter("accessKey");
            String randomStr = request.getParameter("randomStr");
            String token = request.getParameter("token");
            Assert.hasText(timestamp, "签名参数不能为空");
            Assert.hasText(accessKey, "签名参数不能为空");
            Assert.hasText(randomStr, "签名参数不能为空");
            Assert.hasText(token, "签名参数不能为空");
            String secretKey = "frommysql";
            ApiToken apiToken = new ApiToken(timestamp, accessKey, secretKey, randomStr);
            if (!token.equals(apiToken.toString())) {
                logger.warn("此token:[{}]为非法请求", token);
                throw new SecurityException("此token为非法请求");
            }
        } catch (Exception e) {
            throw new ZuulException(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        }
        return null;
    }


}
